local ROT = require 'lib.rotLua.src.rot'

local state = ROT.Class:extend()

function state:init(game, play)
    self.game = game
    self.play = play

    self.map = ROT.Type.Grid()
    self.mask = ROT.Type.Grid()
    self.rotmap = ROT.Map.Cellular:new(80, 25)

    self.rotmap:randomize(0.51)

    for x = 1, 2 do for y = 1, 25 do
        self.rotmap._map[x][y]=0
    end end

    for x = 79, 80 do for y = 1, 25 do
        self.rotmap._map[x][y]=0
    end end

    for y = 1, 2 do for x = 1, 80 do
        self.rotmap._map[x][y]=0
    end end

    for y = 24, 25 do for x = 1, 80 do
        self.rotmap._map[x][y]=0
    end end

    for i = 1, 9 do
    
        self.rotmap:create(function (x, y, val)
            self.map:setCell(x, y, (self.map:getCell(x, y) or 0) + val)
            self.mask:setCell(x, y, val)
        end)
    end
end

function state:update()
    local play = self.play
    local display = self.game.display
    local player = self.game.player
    local scene = self.game.scene
    display:clear()
    for x = 1, display:getWidth() do for y = 1, display:getHeight() do
        t = self.map:getCell(x, y) or 0
        display:write(t == 0 and ' ' 
                or t == 9 and '.'
                or t, 
            x, y, { 80, (t-6) * 40, (7-t) * 40 },
            self.mask:getCell(x, y) == 1 and {0,30,0} or {0,0,30})
    end end
end

function state:keypressed(key)
    local game = self.game

    if key == '\27' then game.state = self.play
    end

end

return state
